package io.github.mengflyl.excel.report.viewer;

import cn.hutool.core.io.FileUtil;
import cn.hutool.setting.Setting;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class ApplicationSetting {

    private final static String settingFile = "application.cfg";
    private static final String recentFilesKey = "recentFiles";
    private final static Setting setting;

    static {
        FileUtil.touch(new File(settingFile).getAbsolutePath());

        setting = new Setting(new File(settingFile).getAbsolutePath());
    }

    public static List<File> getRecentFiles() {

        final Map<String, String> recentFiles = setting.getMap(recentFilesKey);
        return recentFiles.keySet().stream().filter(s -> {
            if (Objects.nonNull(s)) {
                if (FileUtil.exist(s)) {
                    return true;
                }
                setting.remove(recentFilesKey, s);
                setting.store();
            }
            return false;
        }).map(File::new).collect(Collectors.toList());
    }

    public static void addRecentFile(File file) {
        setting.putByGroup( file.getAbsolutePath(),recentFilesKey, "");
        setting.store();
    }

    public static void removeRecentFile(File file) {
        setting.remove(recentFilesKey, file.getAbsolutePath());
    }
}
